using System;
using System.Collections.Generic;
using System.Text;
using AandEDLL.DataAccess.CategoryDSTableAdapters;
using AandEDLL.DataAccess.ItemDSTableAdapters;
using AandEDLL.DataAccess.UserDSTableAdapters;
using AandEDLL.DataAccess.Visit;

namespace AandEDLL.DataAccess.Visit
{
    public class ValidationVisitor : Visitor
    {

        private static ValidationVisitor validationVisitor;

        private ValidationVisitor()
        {

        }

        public static ValidationVisitor getInstance()
        {
            if (validationVisitor == null)
                validationVisitor = new ValidationVisitor();

            return validationVisitor;
        }

        public void visit(Category category)
        {
            if (category.Name == null)
            {
                throw new Exception("Category name is null");
            }
            else if (category.Name == "") 
            {
                throw new Exception("Category name is blank.");
            }

            CategoryTableAdapter cta = new CategoryTableAdapter();
            CategoryDS.CategoryDataTable table = cta.GetData();

            List<Category> list = new List<Category>();
            foreach (CategoryDS.CategoryRow row in table)
            {
                if (row.Name == category.Name)
                    throw new Exception(row.Name + " is already in the database");
            }

            if (category.Name != null && category.Name.Length > 50)
                category.Name = category.Name.Substring(0, 50);
            if (category.Description != null && category.Description.Length > 50)
                category.Description = category.Description.Substring(0, 50);
        }

        public void visit(User user)
        {
            UserTableAdapter uta = new UserTableAdapter();

            // Verify username/password not already in use
            UserDS.UserDataTable dt = uta.GetData();
            UserDS.UserRow[] rows = (UserDS.UserRow[])dt.Select("[UserName] = '"
                + user.UserName + "' AND [Password] = '" + user.Password + "'");

            if (rows.Length > 0)
                throw new Exception("User name / Password already in use");

        }

        public void visit(Item item)
        {
            if((item.ItemName == null)||(item.ItemName == ""))
            {
                throw new Exception("Item name is required");
            }
            //Accessor now handling validation to database
            if (item.ItemName != null && item.ItemName.Length > 255)
                item.ItemName = item.ItemName.Substring(0, 255);
            if (item.Description != null && item.Description.Length > 255)
                item.Description = item.Description.Substring(0, 255);
            if (item.URL != null && item.URL.Length > 120)
                item.URL = item.URL.Substring(0, 120);
        }
    }
}
